layui.use(['layer', 'form', 'admin', 'ax', 'dict', 'laydate', 'upload', 'layedit', 'xmSelect'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var dict = layui.dict;
    var upload = layui.upload;//获取自定义模块
    var layedit = layui.layedit;
    var xmSelect = layui.xmSelect;
    var laydate = layui.laydate;

    dict.renderDictAll(); //渲染

    //日期时间范围
    laydate.render({
        elem: '#buyDate',
        type: 'datetime'
    });

    // 表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        data.field.code = $('#code').val();
        data.field.name = $('#name').val();
        data.field.extraDesc = $('#extraDesc').val();

        layer.load(0, {
            shade: [0.3, '#393D49'],
        }); //上传loading
        $.ajax({
            url: Feng.ctxPath + "/erya/rawmaterial/addData",
            type: "post", // 请求类型
            data: data.field,
            dataType: 'json',
            async: true, // 是否异步
            success: function (data) {
                if(data.code===200){
                    Feng.success("添加成功！");
                    //传给上个页面，刷新table用
                    admin.putTempData('formOk', true);
                    //关掉对话框
                    admin.closeThisDialog();
                }else {
                    layer.open({title: '失败', content: ''+data.message});
                    layer.closeAll('loading'); //关闭loading
                }
            },
            error: function (data) {
                layer.closeAll('loading');
                Feng.error("添加失败！" + data.responseJSON.message)
            }
        });

        //添加 return false 可成功跳转页面
        return false;
    });

    $.ajax({
        url: Feng.ctxPath + "/erya/rawmaterialdictionary/listAdd", // 替换为你的API端点
        type: 'POST',
        dataType: 'json',
        success: function(data){
            if (data.data.length === 0) {
                $('#materialCode').html('请先添加食材名称');
                return;
            }
            var options = '<option value="">请选择食材名称</option>';
            // 循环数据，构建下拉选项
            for(var i = 0; i < data.data.length; i++){
                options += '<option value="' + data.data[i].code + '">' + data.data[i].name + '</option>';
            }
            // 将选项添加到下拉框
            $('#materialCode').html(options);
            // 更新下拉框
            form.render('select');
        }
    });

});